import random

from django import http
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.verifications import serializers
from libs.captcha.captcha import captcha


class ImageCodeView(APIView):
    def get(self,request,image_code_id):
        text,image_data = captcha.generate_captcha()

        redis_conn = get_redis_connection('code')

        redis_conn.setex('image_code_%s'%image_code_id,300,text)

        response = http.HttpResponse(image_data)
        response['Content-Type'] = 'image/png'
        return response

class SmsCodeView(GenericAPIView):
    serializer_class = serializers.SmsCodeSerializer
    def get(self,request,mobile):

        # 1,获取参数
        dict_data = request.query_params

        # 2,创建序列化器,校验
        serializer = self.get_serializer(data=dict_data)
        serializer.is_valid(raise_exception=True)

        # 3,发送短信
        sms_code = '%06d'%random.randint(0,99999)
        print("sms_code=%s"%sms_code)



        # from celery_tasks.sms.tasks import send_sms_code
        # send_sms_code.delay(mobile,sms_code)


        # 4,短信入库
        redis_conn = get_redis_connection('code')
        sms_flag = redis_conn.get('sms_flag_%s'%mobile)

        if sms_flag:
            return Response({'errmsg':'频繁发送'},status=status.HTTP_400_BAD_REQUEST)

        redis_conn.setex("sms_code_%s"%mobile,300,sms_code)
        redis_conn.setex("sms_flag_%s"%mobile,60,True)

        # result = CCP().send_template_sms(mobile,[sms_code,5],1)
        #
        # if result == -1:
        #     return http.HttpResponseBadRequest("发送失败")

        # 5,返回响应
        return Response(status=status.HTTP_200_OK)